package com.example.yingjiguanli_demo.service.impl;

import com.example.yingjiguanli_demo.mapper.LeaderboardMapper;
import com.example.yingjiguanli_demo.pojo.Leaderboard;
import com.example.yingjiguanli_demo.pojo.Matches;
import com.example.yingjiguanli_demo.mapper.MatchesMapper;
import com.example.yingjiguanli_demo.service.IMatchesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yingjiguanli_demo.utils.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author scj
 * @since 2024-11-15
 */
@Service
public class MatchesServiceImpl extends ServiceImpl<MatchesMapper, Matches> implements IMatchesService {

    private static final String MATCH_QUEUE = "matchQueue"; // Redis 中存储匹配队列的键名

    @Autowired
    private RedisTemplate<String, String> redisTemplate; // 使用 RedisTemplate 操作 Redis

    /**
     * 将用户加入匹配队列，并尝试匹配对手
     *
     * @param userId 当前用户的 ID
     * @return 匹配成功的对手用户 ID，如果未匹配到，则返回 null
     */
    @Override
    public String matchUser(Long userId) {
        String opponentId = redisTemplate.opsForList().leftPop("matchQueue", 5, TimeUnit.SECONDS);

        if (opponentId != null) {
            return opponentId; // 返回匹配到的对手 ID
        } else {
            redisTemplate.opsForList().rightPush("matchQueue", String.valueOf(userId));
            return null; // 表示等待
        }
    }

    @Autowired
    private MatchesMapper matchesMapper;

    @Autowired
    private LeaderboardMapper leaderboardMapper;

    /**
     * 记录比赛结果并更新排行榜
     */
    @Transactional
    @Override
    public void recordMatchResult(Integer user1Id, Integer user2Id, Integer user1Score, Integer user2Score, Integer subjectId) {
        // 1. 记录比赛到 Matches 表
        Matches match = new Matches();
        match.setUser1Id(user1Id);
        match.setUser2Id(user2Id);
        match.setUser1Score(user1Score);
        match.setUser2Score(user2Score);
        match.setSubjectId(subjectId);
        match.setStartTime(LocalDateTime.now());
        match.setEndTime(LocalDateTime.now()); // 根据实际比赛结束时间设置
        match.setResult(determineResult(user1Score, user2Score));
        matchesMapper.insert(match);

        // 2. 更新用户1的排行榜数据
        updateLeaderboard(user1Id, user1Score, user2Score);

        // 3. 更新用户2的排行榜数据
        updateLeaderboard(user2Id, user2Score, user1Score);
    }

    /**
     * 根据用户得分计算比赛结果
     */
    private String determineResult(Integer user1Score, Integer user2Score) {
        if (user1Score > user2Score) {
            return "用户1胜";
        } else if (user1Score < user2Score) {
            return "用户2胜";
        } else {
            return "平局";
        }
    }

    /**
     * 更新排行榜数据
     */
    private void updateLeaderboard(Integer userId, Integer userScore, Integer opponentScore) {
        // 查询用户的现有排行榜数据
        Leaderboard leaderboard = leaderboardMapper.selectById(userId);
        boolean isNewRecord = false;

        if (leaderboard == null) {
            // 如果用户还没有记录，创建一个新的排行榜记录
            leaderboard = new Leaderboard();
            leaderboard.setUserId(userId);
            leaderboard.setTotalScore(0);
            leaderboard.setWinCount(0);
            leaderboard.setLoseCount(0);
            leaderboard.setDrawCount(0);
            isNewRecord = true;
        }

        // 更新总分
        leaderboard.setTotalScore(leaderboard.getTotalScore() + userScore);

        // 更新胜负平记录
        if (userScore > opponentScore) {
            leaderboard.setWinCount(leaderboard.getWinCount() + 1);
        } else if (userScore < opponentScore) {
            leaderboard.setLoseCount(leaderboard.getLoseCount() + 1);
        } else {
            leaderboard.setDrawCount(leaderboard.getDrawCount() + 1);
        }

        // 更新最后更新时间
        leaderboard.setLastUpdated(LocalDateTime.now());

        // 更新数据库
        if (isNewRecord) {
            leaderboardMapper.insert(leaderboard);
        } else {
            leaderboardMapper.update(leaderboard);
        }
    }

}
